const jwt = require("jsonwebtoken");

const {
    createUser,
    getUerInfo,
    updateById,
    findUsers,
    delUser,
} = require("../service/user.service");

const {userRegisterError, invalidPassword, failOperation} = require("../constant/err.type");

const {JWT_SECRET} = require("../config/config.default");
const bcrypt = require("bcryptjs");
const {sucOperation} = require("../constant/success.type");

class UserController {
    //注册
    async register(ctx, next) {
        // 1. 获取数据

        // 2. 操作数据库
        try {
            const res = await createUser(ctx.request.body);
            // 3. 返回结果
            ctx.body = {
                code: 0,
                message: "用户注册成功",
                result: {
                    id: res.id,
                    user_name: res.user_name,
                },
            };
        } catch (err) {
            console.log(err);
            ctx.app.emit("error", userRegisterError, ctx);
        }
    }

    // 登录
    async login(ctx, next) {
        const {user_name} = ctx.request.body;

        // 1. 获取用户信息(在token的payload中, 记录id, user_name, is_admin)
        try {
            // 从返回结果对象中剔除password属性, 将剩下的属性放到res对象
            const {password, nick_name, ...res} = await getUerInfo({user_name});

            ctx.body = {
                code: 0,
                message: "用户登录成功",
                result: {
                    nick_name,
                    token: jwt.sign(res, JWT_SECRET, {expiresIn: "1d"}),
                },
            };
        } catch (err) {
            console.error("用户登录失败", err);
        }
    }

    // 修改密码
    async changePassword(ctx, next) {
        // 1. 获取数据
        const id = ctx.state.user.id;
        const password = ctx.request.body.password;

        // 2. 操作数据库
        if (await updateById({id, password})) {
            ctx.body = {
                code: 0,
                message: "修改密码成功",
                result: "",
            };
        } else {
            ctx.body = {
                code: "10007",
                message: "修改密码失败",
                result: "",
            };
        }
        // 3. 返回结果
    }

    // 查询用户列表
    async findAll(ctx) {
        // 1. 解析pageNum和pageSize
        const {pageNum = 1, pageSize = 10, nick_name} = ctx.request.body;
        // 2. 调用数据处理的相关方法
        const res = await findUsers({pageNum, pageSize, nick_name});
        // 3. 返回结果
        ctx.body = {
            code: 0,
            message: "获取用户列表成功",
            result: res,
        };
    }

    // 获取用户信息
    async getUser(ctx) {
        const {id} = ctx.state.user;
        const {nick_name, is_admin, user_name, money} = await getUerInfo({id});
        ctx.body = {
            code: 0,
            message: "获取用户昵称成功",
            result: {
                nick_name,
                is_admin,
                user_name,
                money
            },
        };
    }

    // 更改用户 Admin 状态
    async updateUser(ctx) {
        let {id, is_admin, password, nick_name} = ctx.request.body;
        if (!id) {
            if (ctx.state.user.is_admin !== 1) {
                id = ctx.state.user.id
            }
        }
        if (await updateById({id, is_admin, password, nick_name})) {
            ctx.body = {
                code: 0,
                message: "更改成功",
            };
        } else {
            ctx.body = {
                code: 500,
                message: "更改失败",
            };
        }
    }

    // 根据id查询用户信息
    async findUserById(ctx) {
        const {id} = ctx.params;

        const result = await getUerInfo({id});
        if (result) {
            ctx.body = {
                code: 0,
                message: "查询成功",
                result,
            };
        }
    }

    // 删除用户
    async delUser(ctx) {
        const {id} = ctx.params;
        if (await delUser(id)) {
            ctx.body = {
                code: 0,
                message: "删除成功",
            };
        } else {
            ctx.body = {
                code: 500,
                message: "删除失败",
            };
        }
    }

    // 修改密码
    async updatePassword(ctx) {
        const {id} = ctx.state.user;
        const {password: oldPWD} = await getUerInfo({id});
        const {password, newPassword} = ctx.request.body;
        // 判断原始密码是否符合
        if (!bcrypt.compareSync(password, oldPWD)) {
            ctx.body = invalidPassword;
            return;
        }
        // 将新密码加密
        const salt = bcrypt.genSaltSync(10);
        // hash保存的是 密文
        const res = await updateById({id, password: bcrypt.hashSync(newPassword, salt)})
        if (res) {
            return ctx.body = {
                ...sucOperation,
                result: res,
            };
        } else {
            return ctx.body = {
                ...failOperation
            };
        }
    }

    // 提现
    async withdraw(ctx) {
        const {id} = ctx.state.user;
        const {money} = ctx.request.body;
        const {money: oldMoney} = await getUerInfo({id});
        if (oldMoney < money) {
            return ctx.body = {
                code: 500,
                message: "余额不足",
            };
        } else {
            const res = await updateById({id, money: oldMoney - money})
            console.log(res,"res")
            if (res) {
                return ctx.body = {
                    ...sucOperation,
                    result: res,
                };
            } else {
                return ctx.body = {
                    ...failOperation
                };
            }
        }
    }
}

module
    .exports = new UserController();
